﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MusicWorks.Web.Logic.Views.Models;
using WebFormsMvp;
using MusicWorks.Web.Logic.Views;
using System.IO;
using MusicWorks.Web.Logic.CatalogService;
using MusicWorks.Web.Logic.Helpers;
using MusicWorks.Web.Logic.ShoppingService.svc;

namespace MusicWorks.Web.Logic.Presenters
{
    public class ProductPresenter : Presenter<IProductView>
    {
        ICatalogService _catalogService;
        IShoppingService _shoppingService;
        ISessionValueProvider _sessionValueProvider;

        public ProductPresenter(IProductView view)
            : this(view, ServiceBroker.CreateCatalogServiceInstance(), ServiceBroker.CreateShoppingServiceInstance(), new CookieSessionValueProvider())
        {
        }


        public ProductPresenter(IProductView view, ICatalogService catalogService, IShoppingService shoppingService, ISessionValueProvider sessionValueProvider)
            : base(view)
        {
            _catalogService = catalogService;
            _shoppingService = shoppingService;
            _sessionValueProvider = sessionValueProvider;

            View.Load += View_Load;
            View.AddToCart += View_AddToCart;
        }

        void View_Load(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(View.ProductId)) throw new FileNotFoundException();

            var product = _catalogService.GetProduct(View.ProductId.ToUpperInvariant(), View.CatalogName);
            if (product == null) throw new FileNotFoundException();

            View.Model = new ProductModel
            {
                Id = product.Id,
                DisplayName = product.DisplayName,
                Description = product.Description,
                FormattedPrice = string.Format("{0:C}", product.ListPrice),
                Url = string.Concat("~/Product.aspx?id=", product.Id)
            };
        }

        void View_AddToCart(object sender, AddToCartEventArgs e)
        {
            if (string.IsNullOrEmpty(e.BasketName)) return;

            var cart = _shoppingService.AddToBasket(_sessionValueProvider.UserId, e.BasketName, View.ProductId, string.Empty, 1, View.CatalogName);
            _sessionValueProvider.BasketId = new Guid(cart.Id);
            _sessionValueProvider.BasketValue = cart.TotalProductItems;
            _sessionValueProvider.ItemsInBasket = Convert.ToInt32(cart.TotalQuantityItems);
        }

        public override void ReleaseView()
        {
            View.Load -= View_Load;
        }
    }
}
